import { FC, useState } from 'react'
import PageContainer from '@/components/PageContainer'
import CustomTable from '@/components/CustomTable'
import { useIndexColumns } from './columns'
import useGetTableData from './useGetTableData'
import { getAppList, addApp, editApp, delApp } from '@/api/system'
import type { TableData } from './types'
import { Form, Space, Button, Modal, Table, message } from 'antd'
import EditForm from '@/components/EditForm'
import { useFormEdit } from './useFormEdit'

const Index: FC = () => {
  const [isModalShow, setIsModalShow] = useState<boolean>(false)
  const [isEdit, setIsEdit] = useState<boolean>(false)
  const [FormEdit] = Form.useForm()
  const [form] = Form.useForm()
  const { tableProps, search } = useGetTableData<TableData>(getAppList, {
    form: form,
    pageSize: 999,
  })

  const onCancel = () => {
    setIsModalShow(false)
    FormEdit.resetFields()
  }
  const onConfirm = async (values: any) => {
    const id = FormEdit.getFieldValue('id')
    let res
    if (!isEdit) {
      res = await addApp(values)
    } else {
      res = await editApp({ id, ...values })
    }
    if (res.code === 200) {
      message.success('操作成功')
      onCancel()
      search()
    }
  }
  const onEdit = (info: TableData) => {
    FormEdit.setFieldsValue(info)
    setIsEdit(true)
    setIsModalShow(true)
  }
  const onDel = async (id: string | number) => {
    const res = await delApp(id)
    if (res.code === 200) {
      message.success('操作成功')
      search()
    }
  }
  return (
    <PageContainer>
      <CustomTable
        extra={
          <Space>
            <Button
              type="primary"
              onClick={() => {
                setIsModalShow(true)
              }}
            >
              新建
            </Button>
          </Space>
        }
        {...tableProps}
        columns={useIndexColumns(onEdit, onDel)}
      />
      <Modal
        title={isEdit ? '编辑应用' : '新建应用'}
        open={isModalShow}
        getContainer={false}
        onOk={() => {
          FormEdit.validateFields().then((values: any) => onConfirm(values))
        }}
        onCancel={onCancel}
      >
        <EditForm editConfig={useFormEdit()} form={FormEdit} />
      </Modal>
    </PageContainer>
  )
}

export default Index
